#include "debug.h"


#define DEBUG_BAUDRATE		115200
#define DEBUG_TX_PIN			GPIO_Pin_2
#define DEBUG_TX_PinSource    GPIO_PinSource2

#define DEBUG_RX_PIN			GPIO_Pin_3
#define DEBUG_RX_PinSource    GPIO_PinSource3

#define	DEBUG_PORT			GPIOA
#define	DEBUG_IO_CLK_EN		RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE)

#define DEBUG_UART			USART2
#define DEBUG_UART_CLK_EN		RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE)

#define DEBUG_GPIO_AF_UART 		GPIO_AF_USART2

void Debug_Init()
{
	GPIO_InitTypeDef GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure;
	DEBUG_UART_CLK_EN;
	DEBUG_IO_CLK_EN;

	GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF;
	GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
	GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_UP;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

	GPIO_InitStructure.GPIO_Pin = DEBUG_TX_PIN;
	GPIO_Init(DEBUG_PORT, &GPIO_InitStructure);
	GPIO_InitStructure.GPIO_Pin = DEBUG_RX_PIN;
	GPIO_Init(DEBUG_PORT, &GPIO_InitStructure);

	GPIO_PinAFConfig(DEBUG_PORT,DEBUG_TX_PinSource,DEBUG_GPIO_AF_UART);
	GPIO_PinAFConfig(DEBUG_PORT,DEBUG_RX_PinSource,DEBUG_GPIO_AF_UART);

	USART_InitStructure.USART_BaudRate 	 = DEBUG_BAUDRATE;
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;
	USART_InitStructure.USART_StopBits   = USART_StopBits_1;
	USART_InitStructure.USART_Parity     = USART_Parity_No ;
	USART_InitStructure.USART_Mode 	    = USART_Mode_Rx | USART_Mode_Tx;
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;

	USART_Init(DEBUG_UART,&USART_InitStructure);
	USART_Cmd(DEBUG_UART,ENABLE);
}

void Debug_Print(char *fmt, ...)
{
	char buff[256];
	uint16_t i=0;
	va_list arg_ptr;
	va_start(arg_ptr, fmt);
	vsnprintf(buff, 256, fmt, arg_ptr);
	while(i<256 && buff[i])
	{
		while(USART_GetFlagStatus(DEBUG_UART, USART_FLAG_TC) == RESET){}
		USART_SendData(DEBUG_UART, (unsigned char)buff[i]);
		i++;
	}
}
